#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

int initConnection(int portno);

int main(int argc, char *argv[])
{
  if(argc != 2)
  {
    fprintf(stderr, "Usage: %s port\n", argv[0]);
    exit(1);
  }
  int sockfd = initConnection(atoi(argv[1]));
  while(true)
  {
      std::cin.get();
      char c = '0';
      write(sockfd, &c, 1);
  }
  return 0;
}


int initConnection(int portno)
{
  struct sockaddr_in serv_addr, cli_addr;
  socklen_t clilen;

  int sockfd = socket(AF_INET, SOCK_STREAM, 0);

  if (sockfd < 0)
  {
    fprintf(stderr, "Unable to open socket!\n");
    return -1;
  }

  //Zero buffer
  bzero((char*) &serv_addr, sizeof(serv_addr));

  serv_addr.sin_family = AF_INET;
  serv_addr.sin_port = htons(portno);
  serv_addr.sin_addr.s_addr = INADDR_ANY;

  //Time to Bind
  if(bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
  {
    fprintf(stderr, "Unable to bind socket.\n");
    return -1;
  }

  //Now time to listen for clients
  listen(sockfd, 5); //5 is number of waiting line
  
  //The system will hang on the following line until it gets a client
  clilen = sizeof(cli_addr);
  int newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);

  if(newsockfd < 0)
  {
    fprintf(stderr, "Error on accepting new client.\n");
    return -1;
  }

  //Successful init
  return newsockfd;
}
